package com.code2roc.jarmanage.servlet.filemanage;

import com.code2roc.jarmanage.db.ConfigDB;
import com.code2roc.jarmanage.model.ConfigDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.EnviromentUtil;
import com.code2roc.jarmanage.util.FileUtil;
import com.code2roc.jarmanage.util.StringUtil;
import com.code2roc.jarmanage.util.ZipUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

@MultipartConfig
public class SystemFileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        String prefix = URLDecoder.decode(req.getParameter("prefix"));
        String autounzip = req.getParameter("autounzip");
        if(StringUtil.isEmpty(prefix)){
            result = Result.errorResult().setMsg("根目录禁止上传文件");
            resp.getWriter().println(result.toString());
        }else{
            Part file = req.getPart("file");
            String basePath = EnviromentUtil.getFileRootHomePath();
            String filePath = basePath + prefix;
            filePath = filePath + File.separator + file.getSubmittedFileName();
            FileUtil.uploadFile(FileUtil.convertStreamToByte(file.getInputStream()), filePath);
            if(!StringUtil.isEmpty(autounzip)){
                ZipUtil.decompress(filePath,basePath + prefix);
                FileUtil.delete(filePath);
            }
            resp.getWriter().println(result.toString());
        }
    }
}
